package com.hq.lib_comview.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import com.hq.lib_comview.common.code.Constants;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;

/**
 * 描述 ：系统处理工具
 * 作者 ：hq
 * 时间 ：2017/8/5 00:46
 */
public class SystemUtils {

    /**
     * 获取版本名称
     *
     * @return
     */
    public static String getVersionName(Context context) {
        String versionCode = "1.0.0";
        try {
            PackageInfo pkginfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionCode = pkginfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static int getVersionCode(Context context) {
        int versionCode = 1;
        try {
            PackageInfo pkginfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionCode = pkginfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取进程名
     *
     * @param mContext
     * @return
     */
    public static String getAppName(Context mContext) {
        String processName = null;
        int pID = android.os.Process.myPid();
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = mContext.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    /**
     * 系统检查
     */
    public static String checkSystem(Activity activity) {
        Context appContext = activity.getApplicationContext();
        String channel = SystemUtils.getMetaData(appContext, Constants.CHANNEL_KEY);
        String versionName = getVersionName(appContext);
        int versionCode = getVersionCode(appContext);
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        float density = metrics.density;
        int dpi = metrics.densityDpi;
        JSONObject json = new JSONObject();
        try {
            json.putOpt("model", Build.MODEL);
            json.putOpt("width", width);
            json.putOpt("height", height);
            json.putOpt("density", density);
            json.putOpt("dpi", dpi);
            json.putOpt("mode", (false ? "debug" : "release"));
            json.putOpt("debug_level", 0);
            json.putOpt("channel", channel);
            json.putOpt("api", Build.VERSION.SDK_INT);
            json.putOpt("android", Build.VERSION.RELEASE);
            json.putOpt("version_name", versionName);
            json.putOpt("version_code", versionCode);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String info = json.toString();
        System.out.println("System Info:" + info);
        return info;
    }

    /**
     * 读取清单文件中的配置
     *
     * @return
     */
    public static String getMetaData(Context context, String key) {
        String value = null;
        try {
            ApplicationInfo appinfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            value = appinfo.metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 进入拨号界面
     *
     * @param mContext
     * @param tel
     */
    public static void telPhone(Context mContext, String tel) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    /**
     * 进入系统设置界面
     */
    protected void requestPermission(Context mContext) {
        // 6.0以上系统才可以判断权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            mContext.startActivity(intent);
            return;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            mContext.startActivity(intent);
            return;
        }
        return;
    }

    /**
     * 获得设备id
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    /**
     * 获取ip
     *
     * @param mContent
     * @return
     */
    public static String getIp(Context mContent) {
        //获取wifi服务
        WifiManager wifiManager = (WifiManager) mContent.getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        return intToIp(ipAddress);
    }

    private static String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

}
